<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\api\controller;

use think\Db;
use app\api\model\UserModel;
use cmf\controller\RestBaseController;
use app\api\model\GoodsModel;

class UserController  extends RestBaseController

{

    /**
     * 
     */
    public function register()
    {

        $model = new UserModel();
        $data = array();
        $vcode = input('param.vcode');
        $parentInfo = $model->getInfo(['vcode'=>$vcode],'id,vcode,mobile');
        if(empty( $parentInfo)){
           $this->error("邀请码不存在无法注册");
       }
       $data['mobile'] = input('param.mobile');
       $data['user_login'] = $data['mobile'];
       $data['user_pass'] = cmf_password(input('param.user_pass'));
       $data['pay_pass'] = cmf_password(input('param.pay_pass'));
       $data['user_status'] = 1;
       $data['user_type'] = 2;
       $data['create_time'] = time();
       $data['parent_id'] = $parentInfo['id'];

       $rel = $model->register($data,2);
       if($rel ==1 ){
           $this->error("账户已存在不能重复注册");
       }

        $hashids=Hashids::instance(6,'mackie');//6为邀请码的长度，mackie为加盐密钥
        $yqm=$hashids->encode($rel['id']);
        $urel = $model->updateInfo(['id'=>$rel['id']],['vcode'=>$yqm]);
        $this->success("注册成功!", ['userinfo' => $rel]);
    }
    public function login(){
       $model = new UserModel();
       $where['mobile'] = input('param.mobile');
       $where['user_pass'] = cmf_password(input('param.user_pass'));
       $userInfo = $model->getInfo($where,'id,vcode,mobile');

       if(empty($userInfo)){
        $this->error("用户名密码错误");
    }
    $token = cmf_generate_user_token($userInfo['id'], 'api');
    $this->success("登录成功!", ['token' => $token]);
}
public function userInfo(){
    $token = input('param.token');
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
     $this->error("Token 过期请重新登录");
 }
 $model = new UserModel();
 $uwhere['id'] = $rel['tokenInfo']['user_id'];
 $field = 'id,user_login,mobile,score,balance,vcode,parent_id';
 $userInfo = $model->getInfo( $uwhere,$field );

 $sfield = 'id,user_id,score,status';
    //  今日静态收益
 $today = strtotime(date("Y-m-d"),time());
 $end = $today+60*60*24;
 $jtodaywhere = ' create_time>='. $today .'  and create_time<'. $end  .' and user_id='.$userInfo['id'] .' and status=1' ;
 $jtodayscore = $model->getsumScore($jtodaywhere);

    // 所有静态收益
 $jsumscore = $model->getsumScore( 'user_id='.$userInfo['id'] .' and status=1');

    // 本周团队收益
 $benzhou_kaishi = strtotime('this week monday'); 
 $tsumscore = $model->getsumScore( 'user_id='.$userInfo['id'] .' and status=2  and create_time='.$benzhou_kaishi);

    //  所有团队收益
 $tsumscore = $model->getsumScore( 'user_id='.$userInfo['id'] .' and status=2');
 $data['userInfo'] = $userInfo;
 $data['todayscore'] =  $jtodayscore;
 $data['sumtodayscore'] =  $jsumscore;
 $data['weekcore'] =  $tsumscore;
 $data['sumweekcore'] =  $tsumscore;
 $this->success("获取成功!", $data );
}
public function score_list(){
 $token = input('param.token');
 $rel = getTokenInfo($token);
 if($rel['state']!=1){
     $this->error("Token 过期请重新登录");
 }
 $model = new UserModel();

 $field = 'id,user_id,score,create_time,status';
 $uwhere = 'status =1 or status=2 and user_id =' .$rel['tokenInfo']['user_id'];
 $scoreList = $model->getScoreList( $uwhere,$field );
 $this->success("获取成功!", ['scoreList '=>$scoreList]);
}
public function order_list(){
        $token = input('param.token');
         $rel = getTokenInfo($token);
         if($rel['state']!=1){
            $this->error("Token 过期请重新登录");
        }
      
        $list=  Db::name('order')->alias('o')->join('portal_post p','o.good_id=p.id')->where('o.user_id', $rel['tokenInfo']['user_id'])
        ->field('o.id,p.post_title,o.user_id,o.num,o.num,o.price,p.thumbnail,o.create_time')->select();
        foreach ($list as $k => $v) {
           $list[$k ]= $v;
           $list[$k ]['time'] =  date("Y-m-d H:i:s",$v['create_time']);
           $list[$k ]['topreward'] = $v['num']*$v['price']*1.5/2;
           $ettime = strtotime(date("Y-m-d"),time()) -strtotime(date("Y-m-d",$v['create_time']));
           $etmoery = $ettime /(24*60*60)  *0.03*$lists[$k ]['topreward'] ;
           $list[$k ]['endreward'] = $etmoery;
        }
   $this->success("获取成功!", ['orderList '=> $list ]);
    }

    public function team_reward(){
        $token = input('param.token');
         $rel = getTokenInfo($token);
         if($rel['state']!=1){
            $this->error("Token 过期请重新登录");
        }
         $model = new UserModel();

         $reward_list = $model->getteamReward(['user_id'=>$rel['tokenInfo']['user_id']]);
         foreach ($reward_list as $k => $v) {
             $reward_list[$k ] = $v;
              $reward_list[$k]['start_time']= date("Y-m-d",$v['create_time']);
              $reward_list[$k]['end_time']= date("Y-m-d",$v['create_time']+28*24*3600);
              $reward_list[$k]['has_score']= $v['score']/4*$v['num'];
         }
         $this->success("获取成功!", ['reward_list '=> $reward_list ]);
    }
    public function add_address(){
      $param = $this->request->param();
     $token = $param['token']  ;
     $tokeninfo = getTokenInfo($token);
     if($tokeninfo['state']!=1){
      $this->error("Token 过期请重新登录");
    }
    $goodsmodel = new GoodsModel();
    unset($param['token']);
    if(isset( $param['id'])){
      $rel = $goodsmodel->edit_address(['id'=> $param['id']],$param);
      if($rel){
         $this->success("修改成功!");
       }
        $this->error("修改失败!");
     
    }else{
       
      $param['user_id'] = $tokeninfo['tokenInfo']['user_id'];
       $rel = $goodsmodel->add_address($param);
       if($rel){
        $this->success("添加成功!");
       }
      
       $this->error("添加失败!");
    }

  }
  public function  get_address(){
    $token = input('param.token');
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
        $this->error("Token 过期请重新登录");
    }
    $model = new GoodsModel();
    $where['state'] = 1;
    $where['user_id'] = $rel['tokenInfo']['user_id'];
    $addressInfo = $model->get_address($where);
    if(empty($addressInfo)){
       $wheres['user_id'] = $rel['tokenInfo']['user_id'];
       $addressInfo = $model->get_address($wheres);
      $this->success("获取成功!", ['addressInfo  '=>$addressInfo ]);
    }
    $this->success("获取成功!", ['addressInfo  '=>$addressInfo ]);
  }

  public function add_order(){

    $token = input('param.token');
    $address_id =  input('param.address_id');
    $goods_id =  input('param.goods_id');
    $goods_num =  input('param.goods_num');
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
      $this->error("Token 过期请重新登录");
    }
    $usermodel = new  UserModel();
    $goodsmodel = new GoodsModel();
    $ufield = 'id,balance,user_login,mobile';
    $userInfo = $usermodel->getInfo(['id'=>$rel['tokenInfo']['user_id']],$ufield);
    $gfield = 'id,price,post_title';
    $goodsInfo = $goodsmodel->goods_info(['id'=>$goods_id],$gfield);
    $sum_moeny = $goodsInfo['price']*$goods_num;
    $endmoeny = $userInfo['balance']-$sum_moeny;
    if($endmoeny>=0){
      $addressInfo = $goodsmodel->get_address(['id'=>$address_id ]);

      $orderdata['order_sn'] = 'SN'.date("YmdHis").$userInfo['id'].$goodsInfo['id'];
      $orderdata['user_name'] = $userInfo['user_login'];
      $orderdata['user_id'] = $userInfo['id'];
      $orderdata['user_phone'] = $userInfo['mobile'];
      $orderdata['good_id'] = $goodsInfo['id'];
      $orderdata['good_name'] = $goodsInfo['post_title'];
      $orderdata['create_time'] = time();
      $orderdata['num'] = $goods_num;
      $orderdata['price'] = $goodsInfo['price'];
      $orderdata['sum_moeny'] = $sum_moeny;
      $orderdata['state'] = 1;
      $orderdata['consignee'] = $addressInfo['consignee'];
      $orderdata['province'] = $addressInfo['province'];
      $orderdata['city'] = $addressInfo['city'];
      $orderdata['district'] = $addressInfo['district'];
      $orderdata['address'] = $addressInfo['address'];
      $orderdata['mobile'] = $addressInfo['mobile'];

      $balancedate['user_id'] = $userInfo['id'];
      $balancedate['create_time'] = $orderdata['create_time'];
      $balancedate['change'] = $sum_moeny;
      $balancedate['balance'] = $endmoeny;
      $balancedate['type'] = 2;
      $addrel = $goodsmodel->buy_order(['id'=>$userInfo['id']],['balance'=>$endmoeny],$orderdata, $balancedate);
      if($addrel==true){
        $this->success('购买成功');
      }else{
        $this->error('购买失败');
      }
     
    }else{
      $this->error("余额不足无法支付，如需购买请尽快充值");
    }
    
  }
  public function yz_paypass(){
    $token = input('param.token');
    $pay_pass = input('param.pay_pass');
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
        $this->error("Token 过期请重新登录");
    }

    $where['pay_pass'] = cmf_password($pay_pass);
    $where['id'] = $rel['tokenInfo']['user_id'];
    $usermodel = new UserModel();
    $rel = $usermodel->getInfo($where,'id');
    if($rel){
      $this->success('支付密码正确');
    }else{
      $this->error('支付密码错误');
    }

  }
  // 上传支付凭证
  public function credentials(){
    $token = input('param.token');
     
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
      $this->error("Token 过期请重新登录");
    }
    $inser['change'] = input('param.change');
    //处理图片上传
      //提交时在浏览器存储的临时文件名称
      if($_FILES['image']['tmp_name']){
        $data['image']=$this->upload();
      }
      
      $inser['user_id'] = $rel['tokenInfo']['user_id'];
      
      $inser['img'] = $data['image'];
      $inser['type'] = 1;
      $inser['state'] = 0;
      $inser['create_time'] = time();
      $inser['bank_type'] = input('param.bank_type');
      $modele = UserModel();
      $return = $modele->add_balanceLog($inser);
      if($return){
        $this->success('上传成功');
      }else{
         $this->error('上传失败');
      }
      
  }
  public function upload(){
        // 获取表单上传的文件，例如上传了一张图片
    $file = request()->file('image');
    if($file){
            //将传入的图片移动到框架应用根目录/public/uploads/ 目录下，ROOT_PATH是根目录下，DS是代表斜杠 / 
      $info = $file->move(ROOT_PATH . 'public' . DS . 'upload'. DS .'py');
      if($info){
        return $info->getSaveName();
      }else{
                // 上传失败获取错误信息
        echo $file->getError();die;
      }
    }
  }
  public function score(){
    $token = input('param.token');
     
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
      $this->error("Token 过期请重新登录");
    }
    $usermodel = new UserModel();
 
    $ufield = 'id,score,user_login,mobile';
    $userInfo = $usermodel->getInfo(['id'=>$rel['tokenInfo']['user_id']],$ufield);
    $where['status'] = 3;
    $where['state'] = 0;
    $where['user_id'] = $userInfo['id'];
    $sum = $usermodel->sum_score($where);
    $endm = $userInfo['score'] -$sum;
    $this->success("获取成功!", ['scoresum  '=>$endm ]);

  }
  public function add_score(){
    $token = input('param.token');
     
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
      $this->error("Token 过期请重新登录");
    }
    $usermodel = new UserModel();
    $score = input('param.score');
    $ufield = 'id,score,user_login,mobile';
    $userInfo = $usermodel->getInfo(['id'=>$rel['tokenInfo']['user_id']],$ufield);
    $inser['status'] = 3;
    $inser['state'] = 0;
    $inser['user_id'] = $userInfo['id'];
    $sum = $usermodel->sum_score($inser);
    $endm = $userInfo['score'] -$sum;
    if($endm <$score ){
        $this->error('积分不足无法提现');
    }
    $inser['type'] = input('param.type');
    $inser['score'] = $score;
    $inser['create_time'] = time();
    
    if($inser['type']==0){
      $inser['bank_name'] = input('param.bank_name');
      $inser['bank_num'] = input('param.bank_num');
      $inser['card_username'] = input('param.card_username');
    }else{
      $inser['usdt_addres'] = input('param.usdt_addres');
    }
    $return = $usermodel->add_scoreLog($inser);
    if($return){
      $this->success('提现成功请等待审核');
    }else{
      $this->error('提现失败');
    }
    
  }
  public function huoqusuoyouxiajideid($id){
    $ids = Db::name('User')->where('parent_id','in',$id)->column('id');
    if (!empty($ids)) {
        $ids=array_merge($ids,$this->huoqusuoyouxiajideid($ids));
    }
    return $ids;
}
  public function my_team(){
    $w=date('w')? date('w'):7;
    $lowtime = mktime(0,0,0,date('m'),date('d')-$w+1,date('Y'));

    $token = input('param.token');
     
    $rel = getTokenInfo($token);
    if($rel['state']!=1){
      $this->error("Token 过期请重新登录");
    }
    $user_id = $rel['tokenInfo']['user_id'];
    $sumid = $this->huoqusuoyouxiajideid($user_id);
    $data['teamcount'] = count($sumid);// 团队人数
    array_push($sumid,$user_id);
    $summoeny = Db::name('order')->where('user_id','in',$sumid)->sum('sum_moeny');
    $data['summoeny'] = $summoeny ; //总业绩
    $zhituiid = Db::name('User')->where(['parent_id'=>$user_id])->column('id');
    $zuituimoeny = Db::name('order')->where('user_id','in',$zhituiid)->sum('sum_moeny');
    $data['zuituimoeny'] = $zuituimoeny ; // 直推业绩
    $weekwhere['create_time'] = $lowtime;
    $weekwhere['user_id'] = $user_id;
    $weekmoeny = Db::name('user_tuanduijiangli_list')->where($weekwhere)->sum('moeny');
    $data['weekmoeny'] = $weekmoeny ; // 周新增

    $user_list = array();
    $model = new UserModel();
     foreach ($zhituiid as $k => $v) {
      $userInfo = $model->getInfo(['id'=>$v],'id,create_time,mobile,user_login');
       $user_list[$k]['id']= $userInfo['id'];
       $user_list[$k]['mobile']= $userInfo['mobile'];
       $user_list[$k]['user_login']= $userInfo['user_login'];
       $user_list[$k]['create_time']= $userInfo['create_time'] ;
       $sumziid = $this->huoqusuoyouxiajideid($v);
       array_push($sumziid,$v);
       $summ = Db::name('order')->where('user_id','in',$sumziid)->sum('sum_moeny');
       $user_list[$k]['sum_moeny']= $summ;// 总业绩

       $tweekwhere['create_time'] = $lowtime;
       $tweekwhere['user_id'] = $v;
       $tweekmoeny = Db::name('user_tuanduijiangli_list')->where($tweekwhere)->sum('moeny');
       $user_list[$k]['week_moeny']= $tweekmoeny;// 周新增
     }
      $data['user_list'] = $user_list ;


    $this->success("获取成功!", ['addressInfo  '=>$data]);

  }


}
